package org.example.dao;

import org.example.exception.AppException;
import org.example.model.Message;
import org.example.model.User;
import org.example.util.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {

    public static int insert(Message msg){
        Connection c = null;
        PreparedStatement p = null;
        try{
            c = Util.getConnection();  //获取连接
            String sql = "insert into message values(null,?,?,?,?)";  //
            p = c.prepareStatement(sql);  //创建操作命令对象
            p.setInt(1,msg.getUserId());
            p.setInt(2,msg.getChannelId());
            p.setString(3,msg.getContent());
            //设置为Date只有年月日，设置为Timestamp有年月日时分秒
            p.setTimestamp(4,new Timestamp(System.currentTimeMillis()));
            int result = p.executeUpdate();
            return result;
        }catch(Exception e){
            throw new AppException("保存消息出错！",e);
        }finally{
            Util.close(c,p);
        }
    }

    public static List<Message> queryByLastLogout(Integer userId) {
        Connection c = null;
        PreparedStatement p = null;
        ResultSet r = null;
        List<Message> list = new ArrayList<>();

        try{
            c = Util.getConnection();  //获取数据库连接对象
            String sql = "select m.*, u.nickName from message m join user u on u.userId = m.userId where m.sendTime > (select lastLogout from user where userId = ?)";
            p = c.prepareStatement(sql); //根据数据库连接对象和sql字符串创建操作命令对象
            p.setInt(1,userId);
            r = p.executeQuery(); //查询的结果集对象
            while(r.next()){
                Message message = new Message();
                //通过查询的结果集字段设置对象属性
                message.setUserId(userId);
                message.setNickName(r.getString("nickName"));
                message.setContent(r.getString("content"));
                message.setChannelId(r.getInt("channelId"));
                list.add(message);
            }
            return list;
        }catch(Exception e){
            throw new AppException("查询用户"+userId+"的历史消息出错",e);
        }finally{
            Util.close(c,p,r);
        }

    }
}
